package com.zhz.common.tool.mybatisplus.base.dal.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.zhz.common.tool.mybatisplus.base.core.contract.BaseParam;
import com.zhz.common.tool.mybatisplus.base.core.contract.Page;

import java.util.List;
import java.util.Objects;

/**
 * 分页工具类
 * @author zhouhengzhe
 */
public class PageUtils {
    public PageUtils() {
    }

    public static <T> com.baomidou.mybatisplus.extension.plugins.pagination.Page<T> getMPlusPage(BaseParam pageRequest) {
        return pageRequest == null ? getMPlusPage(1L, 10L) : getMPlusPage(pageRequest.getPage(), pageRequest.getLimit());
    }

    public static <T> com.baomidou.mybatisplus.extension.plugins.pagination.Page<T> getMPlusPage(long current, long size) {
        return new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size < 0L ? 10L : size);
    }

    public static <V, D> Page<V> transformToVoPage(Page<D> dtoPage, List<V> voList) {
        return new Page(voList, dtoPage.getTotal());
    }

    public static <T> IPage<T> getPage(T entity, BaseParam request) {
        long curPage = 1L;
        long limit = 10L;
        curPage = request.getPage();

        limit = request.getLimit();

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<T> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(curPage, limit);
        if (Objects.isNull(request.getOrderField())) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(request.isAsc());
            orderItem.setColumn("id");
            page.addOrder(orderItem);
        }

        if (Objects.nonNull(request.getOrderField())) {
            String[] columns = getColumns(request.getOrderField());
            List<OrderItem> items;
            if (request.isAsc()) {
                items = OrderItem.ascs(columns);
            } else {
                items = OrderItem.descs(columns);
            }

            page.addOrder(items);
        }

        return page;
    }

    private static String[] getColumns(String orderField) {
        return orderField.split(",");
    }
}